package com.hnust.service.impl;

import com.hnust.dao.*;
import com.hnust.domain.*;
import com.hnust.domain.record.*;
import com.hnust.service.SubjectService;
import com.hnust.util.IDUtil;
import com.hnust.util.JwtToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class SubjectImpl implements SubjectService {
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private QuestionDao questionDao;
    @Autowired
    private AlternativeAnswerDao alternativeAnswerDao;
    @Autowired
    private CourseDao couresDao;
    @Autowired
    private CourseGroupDao courseGroupDao;
    @Autowired
    private TeaCourseGroupDao teaCourseGroupDao;
    @Autowired
    private CourseTargetDao courseTargetDao;
    @Autowired
    private ChapterDao chapterDao;

    //获取题目列表
    @Override
    public List<SubjectDataRecord> getQuestionList(String course_id, String token,String id,int currentPage,int rows) throws Exception {
        Map<String, String> map = null;
        Map<String,Object> result =null;
        String idInToken;
        String passwordInToken;
        try{
            map = JwtToken.verifyToken(token);
            idInToken = map.get("id");
            passwordInToken = map.get("password");
        }catch (Exception e){
            return null;
        }
        Teacher teacher = teacherDao.getTeacher(id);
        String password=teacher.getPassword();
        if(!passwordInToken.equals(password)){
            return null;
        }
        currentPage=currentPage*rows;

        List<Question> questionList = questionDao.getQuestionList(course_id,currentPage,rows);
        Integer totalCount = questionDao.getQuestionListCount(course_id);
        Integer totalPage = (int)Math.ceil(totalCount/(double)rows);
        //List<QuestionRecordRecordRecord> questionRecordRecordRecordList = new ArrayList<>();
        Boolean right = true;
        List<SubjectDataRecord> SubjectDataRecordList = new ArrayList<>();
        try {
            for (Question item:questionList){
                String course_name = couresDao.getCourse(item.getCouId());
                QuestionType questionType =questionDao.getCourseQuesTypeList(item.getQueTypId());
                Chapter chapter = chapterDao.getChapterInfo(item.getCouId(),item.getChaId());
                if(chapter==null){
                    throw new Exception("获取章节失败");
                }
                String content = chapter.getChapter()+"."+chapter.getFirst()+"."+chapter.getSecond()+"."+chapter.getThird()+" "+chapter.getName();
                CourseTarget couTagContent = courseTargetDao.getCourseTargetById(item.getCouTarId());

                SubjectDataRecord SubjectDataRecord = new SubjectDataRecord();
                SubjectDataRecord.setId(item.getQueId());
                SubjectDataRecord.setContent(item.getContent());
                SubjectDataRecord.setCourse_name(course_name);
                SubjectDataRecord.setCourse_id(item.getCouId());
                SubjectDataRecord.setChapter_name(content);
                SubjectDataRecord.setChapter_id(item.getChaId());
                SubjectDataRecord.setType_name(questionType.getName());
                SubjectDataRecord.setType_id(item.getQueTypId());
                SubjectDataRecord.setDifficult(item.getLevel());
                SubjectDataRecord.setResolve(item.getAnalysis());
                SubjectDataRecord.setKnowledgePointer(item.getPoint());
                SubjectDataRecord.setCourseTarget(couTagContent.getContent());
                SubjectDataRecord.setCourseTargetId(item.getCouTarId());
                List<AnswerObjRecord> answerObjList = new ArrayList<>();
                SubjectDataRecord.setTotal(totalCount);
                List<AlternativeAnswer> alternativeAnswerList = alternativeAnswerDao.getQuestionAnswerList(item.getQueId());
                for (AlternativeAnswer alternativeAnswer:alternativeAnswerList){
                    if (alternativeAnswer.getRight() == 1){
                        right=true;
                    }else {
                        right=false;
                    }
                    AnswerObjRecord answerObj = new AnswerObjRecord();
                    answerObj.setRight(right);
                    answerObj.setAltAnsId(alternativeAnswer.getAltAnsId());
                    answerObj.setContent(alternativeAnswer.getContent());
                    answerObjList.add(answerObj);
                    SubjectDataRecord.setAnswer(answerObjList);
                }

                SubjectDataRecordList.add(SubjectDataRecord);

            }
        }catch (Exception e){
            throw e;
        }
       return  SubjectDataRecordList;
    }
    //获取课程
    @Override
    public List<CourseData> getCourseData(String id, String token){
        Map<String, String> map = null;
        Map<String,Object> result =null;
        String idInToken;
        String passwordInToken;
        try{
            map = JwtToken.verifyToken(token);
            idInToken = map.get("id");
            passwordInToken = map.get("password");
        }catch (Exception e){
            return null;
        }
        Teacher teacher = teacherDao.getTeacher(id);
        String password=teacher.getPassword();
        if(!passwordInToken.equals(password)){
            return null;
        }
        List<CourseData> courseGroupData = courseGroupDao.getCourseDataByteaId(id);
        if(courseGroupData.size()==0){
            return null;
        }
//        List<String> courseGroupData = teaCourseGroupDao.getCourseGroupData(id);
//        List<CourseData> courseDataList = new ArrayList<>();
//        CourseData courseData = new CourseData();
//        boolean flag = true;
//        for (String item:courseGroupData){
//            String courseId = courseGroupDao.getCourseId(item);
//            String courseName = couresDao.getCourse(courseId);
//            courseData.setId(courseId);
//            courseData.setName(courseName);
//            for (CourseData courseDataItem:courseDataList){
//                if (courseDataItem.getId() == courseId){
//                     flag = false;
//                    break;
//                }
//            }
//            if (flag==true){
//                courseDataList.add(courseData);
//            }else {
//                continue;
//            }
//        }
//        return courseDataList;
        return courseGroupData;
    }
    //搜索课程题目
    @Override
    public List<SubjectDataRecord> getCourseSubByCon(String course_id,String keyword,String token,String id,int currentPage,int rows){
        Map<String, String> map = null;
        Map<String,Object> result =null;
        String idInToken;
        String passwordInToken;

        //关键字处理 删除前后空格
        if (keyword!=null){
            keyword = keyword.trim();
        }

        try{
            map = JwtToken.verifyToken(token);
            idInToken = map.get("id");
            passwordInToken = map.get("password");
        }catch (Exception e){
            return null;
        }
        Teacher teacher = teacherDao.getTeacher(id);
        String password=teacher.getPassword();
        if(!passwordInToken.equals(password)){
            return null;
        }
        currentPage=currentPage*rows;
        List<Question> questionList = questionDao.queryQuestionList(course_id,keyword,currentPage,rows);
        Integer totalCount = questionDao.queryQuestionListCount(keyword,course_id);
        List<SubjectDataRecord> subjectDataList = new ArrayList<>();
        Boolean right = true;
        try {
            for (Question item:questionList){

                String course_name = couresDao.getCourse(item.getCouId());
                QuestionType questionType =questionDao.getCourseQuesTypeList(item.getQueTypId());
                String type_name = questionType.getName();
                Chapter chapter = chapterDao.getChapterInfo(item.getCouId(),item.getChaId());
                if(chapter==null){
                    throw new Exception("获取章节失败");
                }
                String content = chapter.getChapter()+"."+chapter.getFirst()+"."+chapter.getSecond()+"."+chapter.getThird()+" "+chapter.getName();
                CourseTarget couTagContent = courseTargetDao.getCourseTargetById(item.getCouTarId());

                SubjectDataRecord subjectData = new SubjectDataRecord();
                subjectData.setId(item.getQueId());
                subjectData.setContent(item.getContent());
                subjectData.setCourse_id(item.getCouId());
                subjectData.setCourse_name(course_name);
                subjectData.setChapter_id(item.getChaId());
                subjectData.setChapter_name(content);
                subjectData.setType_id(item.getQueTypId());
                subjectData.setType_name(type_name);
                subjectData.setDifficult(item.getLevel());
                subjectData.setResolve(item.getAnalysis());
                subjectData.setKnowledgePointer(item.getPoint());
                subjectData.setCourseTargetId(item.getCouTarId());
                subjectData.setCourseTarget(couTagContent.getContent());
                subjectData.setQueAccess(item.getQueAccess());
                subjectData.setTotal(totalCount);
                List<AnswerObjRecord> answerObjList = new ArrayList<>();
                List<AlternativeAnswer> alternativeAnswerList = alternativeAnswerDao.getQuestionAnswerList(item.getQueId());
                for (AlternativeAnswer alternativeAnswer:alternativeAnswerList){
                    //从int转布尔类型
                    right= alternativeAnswer.getRight() == 1;
                    AnswerObjRecord answerObj = new AnswerObjRecord();
                    answerObj.setRight(right);
                    answerObj.setContent(alternativeAnswer.getContent());
                    answerObj.setAltAnsId(alternativeAnswer.getAltAnsId());
                    answerObjList.add(answerObj);
                    subjectData.setAnswer(answerObjList);
                }
                subjectDataList.add(subjectData);
            }


        }catch (Exception e){
            return null;
        }
        return subjectDataList;

    }

    //删除题目
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public String delCourseSub(String subject_id,String token,String id) throws Exception {
        Map<String, String> map = null;
        Map<String,Object> result =null;
        String idInToken;
        String passwordInToken;
        try{
            map = JwtToken.verifyToken(token);
            idInToken = map.get("id");
            passwordInToken = map.get("password");
        }catch (Exception e){
             throw new Exception("验证失败");
        }
        Teacher teacher = teacherDao.getTeacher(id);
        String password=teacher.getPassword();
        if(!passwordInToken.equals(password)){
            return null;
        }
        try {
            Integer deleteQuestionAnswer = questionDao.deleteQuestionAnswer(subject_id);
            Integer deletePaperQuestion = questionDao.deletePaperQuestion(subject_id);
            Integer deleteQuestion = questionDao.deleteQuestion(subject_id);
            Integer deleteQuestionRecord = questionDao.deleteQuestionRecord(subject_id);
           return "删除成功";
        }catch (Exception e){
            throw new Exception("删除失败");
        }
    }
    //获取题目题型
    public List<QuestionTypeRecord> questionType(String token, String id, String course_id){
        Map<String, String> map = null;
        Map<String,Object> result =null;
        String idInToken;
        String passwordInToken;
        try{
            map = JwtToken.verifyToken(token);
            idInToken = map.get("id");
            passwordInToken = map.get("password");
        }catch (Exception e){
            return null;
        }
        Teacher teacher = teacherDao.getTeacher(id);
        String password=teacher.getPassword();
        if(!passwordInToken.equals(password)){
            return null;
        }
        List<String> courseQuesList = questionDao.getCourseQuestionList(course_id);
        List<QuestionTypeRecord> questionTypes = new ArrayList<>();
        try {
           for (String item:courseQuesList){
               QuestionType questionTypeId = questionDao.getCourseQuesTypeList(item);
               QuestionTypeRecord questionType = new QuestionTypeRecord();
               int typeId = Integer.parseInt(item);
               questionType.setId(typeId);
               questionType.setName(questionTypeId.getName());
               questionTypes.add(questionType);
           }
        }catch (Exception e){
            return null;
        }
        return questionTypes;
    }
    //获取课程目标
    public List<CourseTargetRecord> getCourseTargetList(String course_id, String token, String id){

        Map<String, String> map = null;
        Map<String,Object> result =null;
        String idInToken;
        String passwordInToken;
        try{
            map = JwtToken.verifyToken(token);
            idInToken = map.get("id");
            passwordInToken = map.get("password");
        }catch (Exception e){
            return null;
        }
        Teacher teacher = teacherDao.getTeacher(id);
        String password=teacher.getPassword();
        if(!passwordInToken.equals(password)){
            return null;
        }
        List<CourseTarget> courseTargetList = courseTargetDao.getCourseTarget(course_id);
        List<CourseTargetRecord> courseTargetRecordList = new ArrayList<>();
        try {
            for (CourseTarget item:courseTargetList){
                CourseTargetRecord courseTargetRecord = new CourseTargetRecord();
                courseTargetRecord.setId(item.getCouTarId());
                courseTargetRecord.setContent(item.getContent());
                courseTargetRecord.setCourseNum(item.getNum());
                courseTargetRecordList.add(courseTargetRecord);
            }
        }catch (Exception e){

            return null;
        }
       return courseTargetRecordList;
    }
    //修改题目
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public String updateSubInfo(SubjectDataRecord subjectData, String token, String id){
        Map<String, String> map = null;
        Map<String,Object> result =null;
        String idInToken;
        String passwordInToken;
        try{
            map = JwtToken.verifyToken(token);
            idInToken = map.get("id");
            passwordInToken = map.get("password");
        }catch (Exception e){
            return null;
        }
        Teacher teacher = teacherDao.getTeacher(id);
        String password=teacher.getPassword();
        if(!passwordInToken.equals(password)){
            return null;
        }
        try{
            int access = 0;
            if(subjectData.getQueAccess()!=null) {
                access = (subjectData.getQueAccess() == 1) ? 1 : 0;
            }
            String queAccess = String.valueOf(access);
            questionDao.modifyQuestionById(subjectData.getId(),subjectData.getContent(),
                    subjectData.getCourse_id(),subjectData.getChapter_id(),subjectData.getType_id(),
                    subjectData.getDifficult(),subjectData.getResolve(),
                    subjectData.getKnowledgePointer(),subjectData.getCourseTargetId(),access);
            List<AnswerObjRecord> answerObjList = subjectData.getAnswer();
            alternativeAnswerDao.deleteQuestionAnswer(subjectData.getId());
            for (AnswerObjRecord answerObj:answerObjList){
                int right = 1;
                    right= answerObj.getRight()==true?1:2;
                    String altId =IDUtil.getPrimaryKey();
                    alternativeAnswerDao.addAnswer(subjectData.getId(),answerObj.getContent(),right,altId);
            }
        }catch (Exception e) {
            return "修改题目失败";
        }
        return "修改题目成功";
    }
    //添加题目
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public String addSub(List<SubjectDataRecord> subjectDataList, String token, String id){
        Map<String, String> map = null;
        Map<String,Object> result =null;
        String idInToken;
        String passwordInToken;
        try{
            map = JwtToken.verifyToken(token);
            idInToken = map.get("id");
            passwordInToken = map.get("password");
        }catch (Exception e){
            return null;
        }
        Teacher teacher = teacherDao.getTeacher(id);
        String password=teacher.getPassword();
        if(!passwordInToken.equals(password)){
            return null;
        }
        for (SubjectDataRecord subjectData:subjectDataList) {

            try{
                String Id =(subjectData.getId() == null)?IDUtil.getPrimaryKey():subjectData.getId();
                int access = 0;
                if(subjectData.getQueAccess()!=null) {
                    access = (subjectData.getQueAccess() == 1) ? 0 : 1;
                }
                questionDao.addQuestion(Id,subjectData.getContent(),
                        subjectData.getCourse_id(),subjectData.getChapter_id(),subjectData.getType_id(),
                        subjectData.getDifficult(),subjectData.getResolve(),
                        subjectData.getKnowledgePointer(),subjectData.getCourseTargetId(),access);
                List<AnswerObjRecord> answerObjList = subjectData.getAnswer();
                for (AnswerObjRecord answerObj:answerObjList){
                    int right = 1;
                    right= answerObj.getRight() ?1:2;
                    String altId =(answerObj.getAltAnsId() == null)?IDUtil.getPrimaryKey():answerObj.getAltAnsId();
                    alternativeAnswerDao.addAnswer(Id,answerObj.getContent(),right,altId);
                }
            }catch (Exception e) {

                return "添加题目失败";
            }
        }
        return "添加题目成功";

    }
    //获取章节列表
    public List<CourseChapter> getCourseChapterList(String course_id,String token,String id){
        Map<String, String> map = null;
        Map<String,Object> result =null;
        String idInToken;
        String passwordInToken;
        try{
            map = JwtToken.verifyToken(token);
            idInToken = map.get("id");
            passwordInToken = map.get("password");
        }catch (Exception e){
            return null;
        }
        Teacher teacher = teacherDao.getTeacher(id);
        String password=teacher.getPassword();
        if(!passwordInToken.equals(password)){
            return null;
        }
        List<Chapter> chapterList = chapterDao.getChapter(course_id);
        List<CourseChapter> courseChapterList = new ArrayList<>();
        for (Chapter item:chapterList){
            String content = item.getChapter()+"."+item.getFirst()+"."+item.getSecond()+"."+item.getThird()+" "+item.getName();
            int isParent = 0;
            CourseChapter courseChapter = new CourseChapter();
            courseChapter.setContent(content);
            courseChapter.setId(item.getChaId());
            Boolean flag = false;//是否为父节点 false：不是父节点 true：是父节点
            Boolean firstFlag = false;
            Boolean secondFlag = false;
            //判断1.0.0.0的情况
            if(item.getFirst()==0){
                for(Chapter first:chapterList){
                    if((first.getFirst()!=0)&&(item.getChapter()==first.getChapter())){
                        //是父节点
                        flag = true;
                        break;
                    }else {
                        continue;
                    }
                }
            }
            //判断1.1.0.0的情况
            if(item.getSecond()==0){
                for(Chapter second:chapterList){
                    if((second.getSecond()!=0)&&(second.getFirst()==item.getFirst())&&(item.getChapter()==second.getChapter())){
                        //是父节点
                        flag=true;
                        break;
                    }else {
                        continue;
                    }
                }
            }
            //判断1.1.1.0的情况
            if(item.getThird()==0){
                for(Chapter third:chapterList){
                    if((third.getThird()!=0)&&(item.getSecond()==third.getSecond())&&
                            (third.getFirst()==item.getFirst())&&(item.getChapter()==third.getChapter())){
                        //是父节点
                        flag=true;
                        break;
                    }else {
                        continue;
                    }
                }
            }
            //判断1.1.1.1的情况
            if(item.getThird()!=0){
                //必定是子节点
                flag=false;
            }
            if(flag==true){
                isParent = 1;
            }else {
                isParent = 0;
            }
            courseChapter.setIsParent(isParent);
            courseChapterList.add(courseChapter);

        }
        Collections.sort(courseChapterList, new Comparator<CourseChapter>() {
            @Override
            public int compare(CourseChapter o1, CourseChapter o2) {
                if(o1.getContent().compareTo(o2.getContent())>0){
                    return 1;
                }else if(o1.getContent().compareTo(o2.getContent())<0){
                    return -1;
                }else{
                    return 0;
                }
            }
        });
        return courseChapterList;
    }

}
